import React, { useState, useEffect } from 'react';
import { Product, Language } from '../../types';
import { getProducts, saveProducts } from '../utils/productStorage';
import ImageUploader from '../components/ImageUploader';
import ConfigView from './ConfigView';

const AdminView: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'products' | 'config'>('products');
  const [products, setProducts] = useState<Product[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [formData, setFormData] = useState<Omit<Product, 'id'>>({
    category: '',
    price: 0,
    name: {
      [Language.EN]: '',
      [Language.CN]: '',
      [Language.ES]: ''
    },
    description: {
      [Language.EN]: '',
      [Language.CN]: '',
      [Language.ES]: ''
    },
    images: [''],
    amazonLink: '',
    alibabaLink: ''
  });

  // 初始化商品数据，从本地存储加载
  useEffect(() => {
    const fetchedProducts = getProducts();
    setProducts(fetchedProducts);
  }, []);

  // 保存商品数据到本地存储
  const saveProductsToStorage = (updatedProducts: Product[]) => {
    saveProducts(updatedProducts);
    setProducts(updatedProducts);
  };

  // 打开添加/编辑模态框
  const openModal = (product?: Product) => {
    if (product) {
      setEditingProduct(product);
      setFormData({
        category: product.category,
        price: product.price,
        name: { ...product.name },
        description: { ...product.description },
        images: [...product.images],
        amazonLink: product.amazonLink || '',
        alibabaLink: product.alibabaLink || ''
      });
    } else {
      setEditingProduct(null);
      setFormData({
        category: '',
        price: 0,
        name: {
          [Language.EN]: '',
          [Language.CN]: '',
          [Language.ES]: ''
        },
        description: {
          [Language.EN]: '',
          [Language.CN]: '',
          [Language.ES]: ''
        },
        images: [''],
        amazonLink: '',
        alibabaLink: ''
      });
    }
    setIsModalOpen(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setIsModalOpen(false);
    setEditingProduct(null);
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    
    // 处理嵌套对象的输入
    if (name.includes('.')) {
      const [parent, child] = name.split('.');
      setFormData(prev => ({
        ...prev,
        [parent]: {
          ...prev[parent as keyof typeof prev],
          [child]: value
        }
      }));
    } else {
      // 处理普通字段
      setFormData(prev => ({
        ...prev,
        [name]: name === 'price' ? parseFloat(value) || 0 : value
      }));
    }
  };

  // 提交表单
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (editingProduct) {
      // 编辑现有商品
      const updatedProducts = products.map(p => 
        p.id === editingProduct.id ? { ...editingProduct, ...formData } : p
      );
      saveProductsToStorage(updatedProducts);
    } else {
      // 添加新商品
      const newProduct: Product = {
        ...formData,
        id: Date.now().toString()
      };
      saveProductsToStorage([...products, newProduct]);
    }
    
    closeModal();
  };

  // 删除商品
  const deleteProduct = (id: string) => {
    if (window.confirm('确定要删除这个商品吗？')) {
      const updatedProducts = products.filter(p => p.id !== id);
      saveProductsToStorage(updatedProducts);
    }
  };

  return (
    <div className="container mx-auto px-4 py-12">
      {/* 管理页面导航 */}
      <div className="mb-8">
        <h2 className="text-4xl font-serif font-bold text-brand-wood mb-4">管理中心</h2>
        <div className="flex border-b border-gray-200">
          <button
            onClick={() => setActiveTab('products')}
            className={`px-6 py-3 text-sm font-bold uppercase tracking-wider transition-colors ${activeTab === 'products' 
              ? 'text-brand-orange border-b-2 border-brand-orange' 
              : 'text-brand-stone hover:text-brand-orange'}`}
          >
            商品管理
          </button>
          <button
            onClick={() => setActiveTab('config')}
            className={`px-6 py-3 text-sm font-bold uppercase tracking-wider transition-colors ${activeTab === 'config' 
              ? 'text-brand-orange border-b-2 border-brand-orange' 
              : 'text-brand-stone hover:text-brand-orange'}`}
          >
            网站配置
          </button>
        </div>
      </div>

      {/* 动态内容 */}
      {activeTab === 'products' ? (
        <>
          <div className="flex justify-between items-center mb-8">
            <h3 className="text-2xl font-serif font-bold text-brand-wood">商品列表</h3>
            <button
              onClick={() => openModal()}
              className="bg-brand-orange text-white px-6 py-3 rounded-full hover:bg-orange-600 transition-colors font-bold shadow-md"
            >
              添加商品
            </button>
          </div>

          {/* 商品列表 */}
          <div className="overflow-x-auto">
            <table className="w-full border-collapse">
              <thead>
                <tr className="bg-brand-cream">
                  <th className="border border-brand-orange/20 px-6 py-3 text-left text-sm font-bold text-brand-wood">ID</th>
                  <th className="border border-brand-orange/20 px-6 py-3 text-left text-sm font-bold text-brand-wood">商品名称</th>
                  <th className="border border-brand-orange/20 px-6 py-3 text-left text-sm font-bold text-brand-wood">分类</th>
                  <th className="border border-brand-orange/20 px-6 py-3 text-left text-sm font-bold text-brand-wood">价格</th>
                  <th className="border border-brand-orange/20 px-6 py-3 text-left text-sm font-bold text-brand-wood">操作</th>
                </tr>
              </thead>
              <tbody>
                {products.map(product => (
                  <tr key={product.id} className="hover:bg-brand-cream/50 transition-colors">
                    <td className="border border-brand-orange/20 px-6 py-4 text-sm">{product.id}</td>
                    <td className="border border-brand-orange/20 px-6 py-4">
                      <div className="font-bold text-brand-wood">{product.name[Language.EN]}</div>
                      <div className="text-sm text-gray-600">{product.name[Language.CN]}</div>
                    </td>
                    <td className="border border-brand-orange/20 px-6 py-4 text-sm">{product.category}</td>
                    <td className="border border-brand-orange/20 px-6 py-4 text-sm font-bold text-brand-orange">${product.price.toFixed(2)}</td>
                    <td className="border border-brand-orange/20 px-6 py-4">
                      <div className="flex gap-2">
                        <button
                          onClick={() => openModal(product)}
                          className="bg-brand-wood text-white px-3 py-1 rounded hover:bg-brand-stone transition-colors text-sm"
                        >
                          编辑
                        </button>
                        <button
                          onClick={() => deleteProduct(product.id)}
                          className="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition-colors text-sm"
                        >
                          删除
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 添加/编辑商品模态框 */}
          {isModalOpen && (
            <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
              <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
                <div className="p-6 border-b border-gray-200">
                  <h3 className="text-2xl font-serif font-bold text-brand-wood">
                    {editingProduct ? '编辑商品' : '添加商品'}
                  </h3>
                </div>
                
                <form onSubmit={handleSubmit} className="p-6 space-y-6">
                  {/* 基本信息 */}
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-brand-wood mb-2">分类</label>
                      <input
                        type="text"
                        name="category"
                        value={formData.category}
                        onChange={handleInputChange}
                        className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-brand-wood mb-2">价格</label>
                      <input
                        type="number"
                        name="price"
                        value={formData.price}
                        onChange={handleInputChange}
                        className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                        min="0"
                        step="0.01"
                        required
                      />
                    </div>
                  </div>

                  {/* 商品名称（多语言） */}
                  <div className="space-y-4">
                    <h4 className="font-bold text-brand-wood">商品名称</h4>
                    <div className="grid md:grid-cols-3 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">英文</label>
                        <input
                          type="text"
                          name="name.EN"
                          value={formData.name[Language.EN]}
                          onChange={handleInputChange}
                          className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                          required
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">中文</label>
                        <input
                          type="text"
                          name="name.CN"
                          value={formData.name[Language.CN]}
                          onChange={handleInputChange}
                          className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                          required
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">西班牙文</label>
                        <input
                          type="text"
                          name="name.ES"
                          value={formData.name[Language.ES]}
                          onChange={handleInputChange}
                          className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                          required
                        />
                      </div>
                    </div>
                  </div>

                  {/* 商品描述（多语言） */}
                  <div className="space-y-4">
                    <h4 className="font-bold text-brand-wood">商品描述</h4>
                    <div className="grid md:grid-cols-3 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">英文</label>
                        <textarea
                          name="description.EN"
                          value={formData.description[Language.EN]}
                          onChange={handleInputChange}
                          className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                          rows={3}
                          required
                        ></textarea>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">中文</label>
                        <textarea
                          name="description.CN"
                          value={formData.description[Language.CN]}
                          onChange={handleInputChange}
                          className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                          rows={3}
                          required
                        ></textarea>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">西班牙文</label>
                        <textarea
                          name="description.ES"
                          value={formData.description[Language.ES]}
                          onChange={handleInputChange}
                          className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                          rows={3}
                          required
                        ></textarea>
                      </div>
                    </div>
                  </div>

                  {/* 图片上传 */}
                  <div className="space-y-4">
                    <h4 className="font-bold text-brand-wood">商品图片</h4>
                    <ImageUploader
                      images={formData.images}
                      onChange={(newImages) => setFormData(prev => ({
                        ...prev,
                        images: newImages
                      }))}
                      maxImages={5}
                    />
                  </div>

                  {/* 外部链接 */}
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-brand-wood mb-2">Amazon链接（可选）</label>
                      <input
                        type="url"
                        name="amazonLink"
                        value={formData.amazonLink}
                        onChange={handleInputChange}
                        className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                        placeholder="https://amazon.com/..."
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-brand-wood mb-2">Alibaba链接（可选）</label>
                      <input
                        type="url"
                        name="alibabaLink"
                        value={formData.alibabaLink}
                        onChange={handleInputChange}
                        className="w-full border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                        placeholder="https://alibaba.com/..."
                      />
                    </div>
                  </div>

                  {/* 表单按钮 */}
                  <div className="flex justify-end gap-4 pt-6 border-t border-gray-200">
                    <button
                      type="button"
                      onClick={closeModal}
                      className="bg-gray-200 text-gray-800 px-6 py-3 rounded-md hover:bg-gray-300 transition-colors font-bold"
                    >
                      取消
                    </button>
                    <button
                      type="submit"
                      className="bg-brand-orange text-white px-6 py-3 rounded-md hover:bg-orange-600 transition-colors font-bold shadow-md"
                    >
                      {editingProduct ? '保存修改' : '添加商品'}
                    </button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </>
      ) : (
        <ConfigView />
      )}
    </div>
  );
};

export default AdminView;
